// pages/index/login/login.js
const app = getApp()
const request = require('../../../utils/request')
const regex = require('../../../utils/regex')

Page({
  data: {},

  onLoad() {
    if (wx.getStorageSync('token')){
      wx.switchTab({
        url: '../index'
      })
    }
  },
  
  toReg:function(){
    wx.navigateTo({
      url: '../login/regMini/regMini'
    })
  },

  toForgetPwd(){
    wx.navigateTo({
      url: '/pages/index/login/forgetPwd/forgetPwd'
    })
  },

  // form 提交
  formSubmit(e) {
    const value = e.detail.value

    if (!value.phone) {
      wx.showToast({
        icon: 'none',
        title: '请输入手机号'
      })
      return
    }

    if (!regex.phone.test(value.phone)) {
      wx.showToast({
        icon: 'none',
        title: '手机号格式错误'
      })
      return
    }

    if (!value.pwd) {
      wx.showToast({
        icon: 'none',
        title: '请输入密码'
      })
      return
    }

    const data = {
      phone: value.phone,
      password: value.pwd
    }

    wx.showLoading()
    request.post('login', data)
      .then(res => {
        wx.hideLoading()
        wx.showToast({
          icon: 'none',
          title: '登录成功'
        })

        app.d.token = res.data.token
        wx.setStorageSync("token", res.data.token)
        wx.setStorageSync("isStaff", res.data.is_yg)
        
        setTimeout(() => void wx.switchTab({
          url: '../index'
        }), 1500)

      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg
        })
      })
      .finally(_ => {
        
      })
  },
})